﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using WebAPI__DI_json.DoMain;
using WebAPI__DI_json.Interface;

namespace WebAPI__DI_json.Implementation
{
    public class EfRespository<T> : IRespository<T> where T : BaseEntity
    {
        private readonly AdminDbContext db;

        public EfRespository(AdminDbContext dbContext)
        {
            db = dbContext;
        }

        private DbSet<T> _entity;

        protected DbSet<T> Entity
        {
            get
            {
                if (_entity == null)
                {
                    _entity = db.Set<T>();
                }
                return _entity;
            }

        }

        //查
        public IQueryable<T> Table
        {
            get
            {
                return Entity;
            }
        }

        public T GetById(int Id)
        {
            return Table.Where(x => x.Id == Id).FirstOrDefault();

        }

        //删
        public void Delete(T entity)
        {
            Entity.Remove(entity);

            db.SaveChanges();
        }

        public void Delete(int Id)
        {
            var Del = Table.Where(x => x.Id == Id).FirstOrDefault();
            Delete(Del);
        }

        //增
        public void Insert(T entity)
        {
            Entity.Add(entity);

            db.SaveChanges();
        }


        public void InsertBulk(IEnumerable<T> list)
        {
            Entity.AddRange(list);
            db.SaveChanges();
        }

        //改
        public void Update(T entity)
        {
            Entity.Update(entity);
            db.SaveChanges();
        }
    }
}
